
import axios from 'axios'
import configObj from '../config'
import { dataType } from './index'
import { dataEncrypt, dataDecrypt } from './wholeEncrypt'
let instance = null
// 根据环境调整服务器地址
// console.log(process.env.NODE_ENV)
// console.log(process.env.API_ROOT)

const header = {
    'Content-Type': 'multipart/form-data'
}
instance = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? "/proxyApi" : config.prod_Api,
    timeout: 5000,
    headers:header
});

//axios全局请求拦截
instance.interceptors.request.use(
    config => {
        config.headers.token =  JSON.parse(localStorage.getItem('state')) ? JSON.parse(localStorage.getItem('state')).token : ''
        if(dataType(config.data) !== 'formdata' && !!!config.data.no_diff && configObj.isEncry){
            config.data = {
              params: {
                cipherText: dataEncrypt(JSON.stringify(config.data)),
              },
            }
          }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);
//axios全局响应拦截
instance.interceptors.response.use(
    response => {
        if(response.data && response.data.cipherText && configObj.isEncry){
            response.data = JSON.parse(dataDecrypt(response.data))
          }
        return response;
    },
    err => {
        return Promise.reject(err)
    }
);

function checkStatus(response) {
    const resp = response.data;
    return new Promise((resolve, reject) => {
        if(response.status === 200){
            resolve({
                success:true,
                data:resp
            })
        }else if(response.status === 401){
                //token失效
                removeSessionstorage('token')
        }else{
            reject(resp)
        }
    })
}

export default {
    get(url,params = {},headers = header){
        return instance({
            method: 'get',
            url,
            params,
            headers
        }).then(checkStatus)
    },
    post(url,data,headers = header){
        return instance({
            method: 'post',
            url,
            data:data,
            headers
        }).then(checkStatus)
    },
    put(url, data, headers = header) {
        return instance({
            method: 'put',
            url,
            data,
            headers
        }).then(checkStatus)
    },
    delete(url, params, headers = header) {
        return instance({
            method: 'delete',
            url,
            params,
            headers
        }).then(checkStatus)
    },
}